var bgCgdContent = {
    initComponent: function () {
        //判断修改状态 不显示合同选择
        if (bgCgdContent.isNew()) {
            $.post($.webPath() + '/htgl/cghtgl/bgcghtSimpleList?cghtId=' + $('#htId_content').val() + '&zt=ysp&htType=' + $("#htType_id").val(), function (data) {
                bgCgdContent.fillHtInfo(data);
                fillFyByCgd();
                bgCgdContent.fillHtmxByHt(data);
                bgCgdContent.showCgdInfo();
                bgCgdContent.changeUI(data);
            },'json');
        } else {
            //到货仓库
            $("#cgd_dhck_id").bgckcombobox();

            //发货单位
            $("#cgd_fhgs_id").xsqyjgcombobox($("#cgd_gys_id").val());

            bgCgdContent.showCgdInfo();
        }

        $("#cgd_ysdw_id").wlscombobox();

        //工程
        $("#cgd_xsd_gc_id").gccombobox();
        //税率
        $('#cgd_sl').slsjzdcombobox("sl");


    },
    initBtn: function () {
        //新增费用明细
        $("#cgd_content_glfy_add").click(function () {
            var data = {
                'sydw.id': null,
                'fylb.id': null,
                'jfsl': 0,
                'dj': 0,
                'je': 0,
                'bz': null
            };
            $("#cgd_fy").edatagrid('appendRow', data);
        });
        //删除合同费用
        $("#cgd_content_glfy_del").click(function () {
            var rows = $("#cgd_fy").edatagrid('getChecked');
            if (rows) {
                $.messager.confirm('提示', '是否确定删除销售费用?', function (r) {
                    if (r) {
                        $.each(rows, function (i, val) {
                            var index = $("#cgd_fy").edatagrid('getRowIndex', val);
                            $("#cgd_fy").edatagrid('deleteRow', index);
                        });
                    }
                });
            }
            $("#cgd_fy").edatagrid('resize');
        });
    },
    fillHtmxByHt: function (data) {
        var href = $.webPath() + '/htgl/cghtgl/bgcghtgl_htmx?cghtId=' + $('#htId_content').val() + '&&htmxIds=' + $('#htmxIds_content').val();
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
            $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
                fillHtmx(href, cddata, data);
            })
        });
    },
    //显示合同内容
    showCgdInfo: function () {
        $("#table_bgCgdContent").show();
    },
    //填充合同内容
    fillHtInfo: function (data) {
        //合同编码
        $("#cgd_cght_htbm").text(data["htbm"]);
        //供应商
        $("#cgd_gys_id").val(data["hzf_id"]);
        $("#cgd_gys_mc").text(data["hzf_jc"] || "");

        //发货单位
        $("#cgd_fhgs_id").xsqyjgcombobox($("#cgd_gys_id").val());

        //采购类型
        $("[name='cgd.cglx']").val(data["cglx"]);

        //申报公司
        $("#cgd_wlfgs_mc").text(data["sbgs_jc"] || "");
        $("[name='cgd.sbgs.id']").val(data["sbgs_id"]);
        //申报部门
//        $("#cgd_wlfbm_mc").text(data["sbbm_qc"] || "");
//        $("[name='cgd.sbbm.id']").val(data["sbbm_id"]);

        //申报人
//        $("#cgd_wlfry_mc").text(data["sbr_xm"] || "");
//        $("[name='cgd.sbr.id']").val(data["sbr_id"]);

        //采购公司
        $("#cgd_cggs_mc").text(data["wlfgs_jc"] || "");
        $("[name='cgd.cggs.id']").val(data["wlfgs_id"]);

        if (data["sbgs_id"] == data["wlfgs_id"]) {
            $("#cgd_xsd_xsgs_jc").text(data["wlfgs_jc"] || "");
            $("[name='cgd.xsd.xsgs.id']").val(data["wlfgs_id"]);
            $("#cgd_xsd_zbcg").unbind('click').bind('click', function () {
                return false;
            });
        } else {
            $("#cgd_xsd_xsgs_jc").text(data["wlfgs_jc"] || "");
            $("[name='cgd.xsd.xsgs.id']").val(data["wlfgs_id"]);
            $("#cgd_xsd_zbcg").attr('checked', 'true');
            $("#cgd_xsd_zbcg").unbind('click').bind('click', function () {
                if ($(this).attr("checked") != undefined && $(this).attr("checked") == "checked") {
                    //TO-DO 赋值公司本部
                    $("#cgd_xsd_xsgs_jc").text(data["wlfgs_jc"] || "");
                    $("[name='cgd.xsd.xsgs.id']").val(data["wlfgs_id"]);
                } else {
                    $("#cgd_xsd_xsgs_jc").text(data["sbgs_jc"] || "");
                    $("[name='cgd.xsd.xsgs.id']").val(data["sbgs_id"]);
                }
            });
        }

        $("#cgd_dhck_id").bgckcombobox();


        //到货仓库
//        if (data["cglxz"] == 'tpcght') {
//            $("#cgd_dhck_id").ckcombobox(data["wlfgs_id"]);
//        } else {
//            $("#cgd_dhck_id").val();
//            $("#cgd_dhck_mc").val();
            //$("#cgd_dhck_id").bgckcombobox();
//        }


        //路径
        $("#cgd_lj_id").val(data["lj_id"]);

        $("#cgd_sl").combobox('setValue', data["sl"] || $("#cgd_sl").combobox("getData")[0].z);

        //利率
        $("#cgd_cght_ll").text(formatLl(data["ll"]) || "");
    },
    changeUI: function (rowData) {
        var lx;
        if (rowData == null) {
            lx = $("[name='cgd.cglx']").val();
        } else {
            lx = rowData["cglxz"];
        }
        //bgCgdContent.showCgdInfo();
        //刷新采购费用的类型
//        if (lx == "zddh") {
//            $("#cgd_dhck_id").combobox({required: false});
//        } else {
//            $("#cgd_dhck_id").combobox({required: true});
//        }
    },
    isNew: function () {
        return $("[name='cgd.id']").val() == "";
    },
    fillData: function () {
        fillHtmxByCgd();
        fillFyByCgd();
    }
};

$(function () {
    bgCgdContent.initComponent();
    bgCgdContent.changeUI(null);
    bgCgdContent.initBtn();
    bgCgdContent.fillData();
})

function fillHtmxByCgd() {
    $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'cd'}, function (cddata) {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm': 'jzfs'}, function (data) {
            fillHtmx($.webPath() + '/cggl/cgdgl/cgdgl_cgmx?cgd.id=' + $("[name='cgd.id']").val() || '', cddata, data);
        })
    });
}

function fillFyByCgd() {
    $.post($.webPath() + '/organ/wls/wlsInuseList', function (jgdata) {
        $.post($.webPath() + '/cwgl/kmys/cyfyys/fylbcombobox', {'gsId': $("[name='cgd.sbgs.id']").val()}, function (data) {
            fillFy($.webPath() + '/cggl/cgdgl/cgdgl_cgfy?cgd.id=' + $("[name='cgd.id']").val() || '', jgdata, data);
        })
    })
}

function fillHtmx(href, cdOptions, fsOptions) {
    $("#cgd_mx").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkOnSelect: false,
        selectOnCheck: false,
        showFooter: true,
        rownumbers: true,
        toolbar: "#cgdgl_cgdmx_toolbar",
        columns: [
            [
                {field: 'wzgg.oldcode', title: '老物资编码', width: 40},
//                {field: 'wzgg.code', title: '新物资编码', width: 40},
                {field: 'wzgg.name', title: '物资名称', width: 30},
                {field: 'wzgg.ggxh', title: '规格型号', width: 30},
                {field: 'wzgg.dw', title: '单位', width: 10},
                {field: 'cd.id', editor: {type: 'combobox', options: {
                    data: cdOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '150'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < cdOptions.length; i++) {
                        if (cdOptions[i].id == value) return cdOptions[i].z;
                    }
                    return value;
                }, title: '产地', width: 30},
                {field: 'jzfs.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'z',
                    multiple: false,
                    panelHeight: '55'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title: '记重方式', width: 25},
                {field: 'js', editor: {type: 'numberbox', options: {min: 0, precision: 0}}, title: '件数',
                    formatter: function (value) {
                        var sl = formatSl(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'sbsl', editor: {type: 'numberbox', options: {min: 0, precision: 4}}, title: '数量',
                    formatter: function (value) {
                        var sl = formatSl(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'hsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'bhsj', editor: {type: 'numberbox', options: {min: 0, precision: 4, groupSeparator: ','}}, title: '不含税单价(元)',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'ph', title: '牌号', editor:{type:'text'}, width: 40}
            ]
        ],
        loadFilter: function (data) {
            var wzggIds = $("#wzggIds_content").val();
            var jhsls = $("#jhsls_content").val();
            var wzggsz = wzggIds.split(",");
            var jhslsz = jhsls.split(",");
            if (bgCgdContent.isNew()) {
                $(data.rows).each(function () {
                    this.js = 1;
                    for (var i = 0; i < wzggsz.length; i++) {
                        if (wzggsz[i] == this['wzgg_id']) {
                            this.sbsl = jhslsz[i];
                        }
                    }
                })
            }
            return data;

        },
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#cgd_mx").edatagrid('editRow', rowIndex);
            var editors = $("#cgd_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var hsjEditor = editors[4];
            var bhsjEditor = editors[5];
            hsjEditor.target.unbind("blur").bind('blur', function () {
                $(hsjEditor.target).numberbox('setValue', $(hsjEditor.target).val());
                $(bhsjEditor.target).numberbox('setValue', tax.getNotIncludingTaxPrice($(hsjEditor.target).numberbox('getValue'), $("#cgd_sl").combobox('getValue')));
                countSumBgCgdmx();
            });
            bhsjEditor.target.unbind("blur").bind('blur', function () {
                $(bhsjEditor.target).numberbox('setValue', $(bhsjEditor.target).val());
                if(!$(hsjEditor.target).numberbox('getValue'))
                    $(hsjEditor.target).numberbox('setValue', tax.getIncludingTaxPrice($(bhsjEditor.target).numberbox('getValue'), $("#cgd_sl").combobox('getValue')));
                countSumBgCgdmx();
            });
        },
        onLoadSuccess: function () {
            countSumBgCgdmx();
        }
    })
}


function fillFy(href, jgOptions, fsOptions) {
    $("#cgd_fy").edatagrid({
        url: href,
        fitColumns: true,
        singleSelect: true,
        fit: true,
        checkbox: true,
        checkOnSelect: false,
        selectOnCheck: false,
        rownumbers: true,
        toolbar: "#cgdgl_cgdfy_toolbar",
        columns: [
            [
                {field: 'checked', checkbox: true},
                {field: 'sydw.id', editor: {type: 'combobox', options: {
                    data: jgOptions,
                    valueField: 'id',
                    textField: 'qc',
                    multiple: false,
                    panelHeight: '200'
                }
                }, formatter: function (value) {
                    for (var i = 0; i < jgOptions.length; i++) {
                        if (jgOptions[i].id == value) return jgOptions[i].qc;
                    }
                    return value;
                }, title: '收益单位', width: 40},
                {field: 'fylb.id', editor: {type: 'combobox', options: {
                    data: fsOptions,
                    valueField: 'id',
                    textField: 'fykmjc',
                    multiple: false,
                    panelHeight: '110',
                    onSelect: function () {
                        var selected = $('#cgd_fy').datagrid('getSelected');
                        var rowIndex = $('#cgd_fy').datagrid('getRowIndex', selected);
                        $("#cgd_fy").edatagrid('editRow', rowIndex);
                        var editors = $("#cgd_fy").datagrid('getEditors', rowIndex);
                        if (editors.length == 0)
                            return;
                        var fylbEditor = editors[1];
                        var jfslEditor = editors[2];
                        var djEditor = editors[3];
                        var jeEditor = editors[4];
                        if ($(fylbEditor.target).combobox('getText') == "运输费") {
                            var jfsl = countSumBgCgdmxforfylbChange('sbsl');
                            $(jfslEditor.target).numberbox('setValue', jfsl);
                            var dj = countSumBgCgdmxforfylbChange('hsj');
                            $(djEditor.target).numberbox('setValue', parseFloat(dj) * 0.4);
                            var je = parseFloat(jfsl) * (parseFloat(dj) * 0.4);
                            $(jeEditor.target).numberbox('setValue', je);
                        } else {
                            $(jeEditor.target).numberbox('setValue', 0);
                            $(djEditor.target).numberbox('setValue', 0);
                            $(jfslEditor.target).numberbox('setValue', 0);
                        }
                    }
                }
                }, formatter: function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].fykmjc;
                    }
                    return value;
                }, title: '费用类别', width: 17},
                {field: 'jfsl', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '计费数量',
                    formatter: function (value) {
                        var sl = formatSl(value, ",");
                        return sl;
                    }, width: 40},
                {field: 'dj', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '单价',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'je', editor: {type: 'numberbox', options: {min: 0, groupSeparator: ',', precision: 4}}, title: '总金额',
                    formatter: function (value) {
                        var sl = formatJe(value, ",");
                        return sl;
                    }, width: 50},
                {field: 'bz', editor: {type: 'text'}, title: '备注', width: 30}
            ]
        ],
        onSelect: function (rowIndex, rowData) {
            //获取每个单元格
            $("#cgd_fy").edatagrid('editRow', rowIndex);
            var editors = $("#cgd_fy").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var fylbEditor = editors[1];
            var jfslEditor = editors[2];
            var djEditor = editors[3];
            var jeEditor = editors[4];

            jfslEditor.target.unbind("blur").bind('blur', function () {
                $(jfslEditor.target).numberbox('setValue', $(jfslEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });
            djEditor.target.unbind("blur").bind('blur', function () {
                $(djEditor.target).numberbox('setValue', $(djEditor.target).val());
                $(jeEditor.target).numberbox('setValue', $(jfslEditor.target).numberbox('getValue') * $(djEditor.target).numberbox('getValue'));
            });
        }
    })
}

$('#bgCgdglForm').tabs({

    border: false,
    onSelect: function (title) {

        if (title == "送货单打印") {
            //判断合同有没有保存
            if (null == $("[name='cgd.id']").val() || $("[name='cgd.id']").val() == '') {
                $('#bgCgdglForm').tabs('select', "送货明细");
                $.messager.alert('提示', '先保存送货单明细，才能编辑送货单打印文本', 'info');
            } else {
                $.ajax({
                    type: "POST",
                    url: $.webPath() + '/cggl/cgdgl/cgdDetail?cgdId=' + $("input[name='cgd.id']").val(),
                    dataType: "html",
                    beforeSend: function () {
                        $.messager.progress();
                    },
                    success: function (data) {
                        $.messager.progress("close");
                        $('#cgddy_cgd_id').html(data);
                        if (data.statusCode == 300) {
                        }
                        if (data.statusCode == 200) {
                        }
                    }
                });
            }

        }
    }
});

//  检查插件
function cgd_checkIsInstall() {
    try {
        var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
        if ((LODOP != null) && (typeof(LODOP.VERSION) != "undefined"))
            alert("本机已成功安装过Lodop控件!\n  版本号:" + LODOP.VERSION);
    } catch (err) {
        alert("Error:本机未安装或需要升级!");
    }
}
;

function createCgdHtml() {
    var LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
    LODOP.SET_PRINT_STYLEA(0, "NotOnlyHighPrecision", true);
    LODOP.PRINT_INIT("预览送货单");
    var strBodyStyle = "<style  type=\"text/css\">" +
        ".textcon{padding:8px;}" +
        ".input-tian{border-top:0 none;border-left:0 none;border-right:0 none;border-bottom: 1px solid black;height:22px;line-height:22px;width:100%;font-weight: bold;}" +
        " select{display:none}" +
        ".tb{width:auto;border-collapse:collapse;border-spacing:0;}" +
        ".tb th{padding:2px 2px 2px 12px;font-size:12px;font-weight:normal;text-align: right;}" +
        ".tb td{padding:2px;font-size:12px;}" +
        ".tb caption{ font-size:24px;height:60px;line-height:20px;}" +
        ".intb{width: 100%;}" +
        ".intb,.intb th,.intb td{border:1px solid black;}" +
        "</style>";
    var strFormHtmltop = strBodyStyle + "<div class='textcon'>" + document.getElementById("cgddy_print_id").innerHTML + "</div>";
    var strFormHtmlbody = strBodyStyle + "<div class='textcon'>" + document.getElementById("cgddy_cgd_id").innerHTML + "</div>";
    var strFormHtmlBottom = strBodyStyle + "<div class='textcon'>" + document.getElementById("cgddy_print_end").innerHTML+"</div>";

    var cgd_cgdh = $("#cgd_cgdh").val();
    var cgd_ewmtime = $("#cgd_ewmtime").val();

//    LODOP.SET_PRINT_PAGESIZE(0, '2640', '2790', "CreateCustomPage");
//    LODOP.ADD_PRINT_HTM(50, 80, "82%", "90%", strFormHtmltop + strFormHtmlbody + strFormHtmlBottom);
//    LODOP.ADD_PRINT_BARCODE(50, "85%", 90, 90, 'QRCode', cgd_cgdh + " " + cgd_ewmtime);
    LODOP.ADD_PRINT_TABLE(135, "1.5%", "90%", 350, strFormHtmlbody);
    LODOP.SET_PRINT_STYLEA(0,"Vorient",3);
    LODOP.ADD_PRINT_HTM(20, "1.5%", "90%", 145, strFormHtmltop);
    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
    LODOP.SET_PRINT_STYLEA(0,"LinkedItem",1);
    LODOP.ADD_PRINT_HTM(495, "1.5%", "90%", 200, strFormHtmlBottom);
    LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
    LODOP.SET_PRINT_STYLEA(0,"LinkedItem",1);
//    LODOP.ADD_PRINT_BARCODE(20, "85%", 90, 90, 'QRCode', cgd_cgdh + " " + cgd_ewmtime);
//    LODOP.SET_PRINT_STYLEA(0, "QRCodeVersion", 3);
    LODOP.ADD_PRINT_TEXT(5,"80%",135,20,"总页号：第#页/共&页");
    LODOP.SET_PRINT_STYLEA(0,"ItemType",2);
    LODOP.SET_PRINT_STYLEA(0,"Horient",1);
    return LODOP;
}

// 打印预览.
function cgd_printPreview() {
    var LODOP = createCgdHtml();
    LODOP.PREVIEW();
}

// 打印
function cgd_print() {
    var LODOP = createCgdHtml();
    LODOP.PRINT();
}

//采购单明细合计
function countSumBgCgdmx() {
    var sumSbsl = 0;
    var sumHsj = 0;
    var sumBhsj = 0;
    var data = $("#cgd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var sbsl = parseFloat(data.rows[i]["sbsl"]);
        var hsj = parseFloat(data.rows[i]["hsj"]);
        var bhsj = parseFloat(data.rows[i]["bhsj"]);
        sbsl = isNaN(sbsl) ? 0 : sbsl;
        hsj = isNaN(hsj) ? 0 : hsj;
        bhsj = isNaN(bhsj) ? 0 : bhsj;
        sumSbsl += sbsl;
        sumHsj += hsj;
        sumBhsj += bhsj;
    }
    addFooter(sumSbsl, sumHsj, sumBhsj);
}

function addFooter(sumSbsl, sumHsj, sumBhsj) {
    var footer = null;
    footer = [
        {"wzgg.code": "合计", "sbsl": formatMoneyFourWei(sumSbsl), "hsj": formatMoneyFourWei(sumHsj), "bhsj": formatMoneyFourWei(sumBhsj)}
    ];
    if (footer != null)
        $("#cgd_mx").edatagrid('reloadFooter', footer);
}

//统计单一属性的方法
function countSumBgCgdmxforfylbChange(property) {
    var sum = 0;
    var data = $("#cgd_mx").edatagrid("getData");
    for (var i = 0; i < data.rows.length; i++) {
        var pro = parseFloat(data.rows[i][property]);
        pro = isNaN(pro) ? 0 : pro;
        sum += pro;
    }
    return sum;
}
